﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BLL;
using DAL.Model;
using Web.Models;
using Option = Web.Models.Option;

namespace RazorQuiz.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index(int id = 1)
        {
            var manager = new QuestionManager();
            var question = manager.GetAquestion(id);
            var disp = new AmericanQuestion
                               {
                                   Id = question.QuestionID,
                                   Question = question.Question1,
                                   Options = new List<Option>()
                               };
            foreach (var opt in question.Options)
                disp.Options.Add(new Option { Description = opt.Description, Id = opt.OptionID, IsSelected = false });

            return View(disp);
        }

        public ActionResult Results()
        {
            var manager = new QuestionManager();

            var answers = manager.GetAnswersForUser(User.Identity.GetNameIdentifier());


            var result = new List<AmericanQuestion>();
            foreach (var answer in answers)
            {

                var answer1 = answer.Question.Options.FirstOrDefault(d => d.OptionID == answer.Answer.optionid);
                if (answer1 == null) continue;
                var q = new AmericanQuestion
                            {
                                Id = answer.Question.QuestionID,
                                Question = answer.Question.Question1,
                                Answer = answer1.Description,
                                IsCorect = answer.Answer.iscorect
                            };

                result.Add(q);
            }



            return View(result);
        }

        public ActionResult Done()
        {
            return View();
        }

        [HttpPost]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Index(FormCollection formCollection)
        {
            int questionID;
            Question next = null;
            if (int.TryParse(formCollection["questionID"], out questionID))
            {
                var manager = new QuestionManager();
                next = manager.GetNextQuestion(questionID);
            }

            int selectedAnswerID;
            if (int.TryParse(formCollection["question"], out selectedAnswerID))
            {
                var manager = new QuestionManager();
                manager.SubmitAnswer(questionID, selectedAnswerID, User.Identity.GetNameIdentifier());
            }

            Response.Redirect(next != null
                                  ? string.Format("/Home/Index/{0}", next.QuestionID)
                                  : string.Format("/Home/Done"));
            return null;
        }

    }
}
